from typing import List
from app.api.deps import CurrentUser, SessionDep
from app.models import Task, TaskDetail, TaskListResponse
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select

router = APIRouter(prefix="/task", tags=["task"])


@router.get("/", response_model=TaskListResponse)
def get_tasks_api(
    session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
):
    if current_user.is_superuser:
        count_statement = select(func.count()).select_from(Task)
        count = session.exec(count_statement).one()
        statement = select(Task).offset(skip).limit(limit).order_by(Task.create_time.desc())
        items = session.exec(statement).all()
    else:
        count_statement = (
            select(func.count())
            .select_from(Task)
            .where(Task.user_id == current_user.id)
        )
        count = session.exec(count_statement).one()
        statement = (
            select(Task)
            .where(Task.user_id == current_user.id)
            .offset(skip)
            .limit(limit)
            .order_by(Task.create_time.desc())
        )
        items = session.exec(statement).all()

    return TaskListResponse(data=items, count=count)

@router.get("/{task_id}", response_model=TaskDetail)
def get_task_by_id_api(
    session: SessionDep, task_id: str, current_user: CurrentUser
) -> TaskDetail:
    statement = select(Task).where(Task.id == task_id)
    task = session.exec(statement).one_or_none()
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    if not current_user.is_superuser and task.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="You do not have permission to access this task")
    return task

